import { $wAxios } from '@/utils/api'

// 必须继承才能使用
class BaseModel {
  public _id: string = ''

  public deleteApi = ''

  // 获取json对象
  public static getJson (obj: BaseModel, keys: string, json = {}) {
    return obj.getJson(keys, json)
  }

  // 根据数据设置对象并获取
  public static creatModelWithJson<T extends BaseModel> (json?: object): T {
    const model = new this()
    model.setDataWithJson(json)
    return model as T
  }

  // 设置数据
  public setDataWithJson (json: {} = {}) {
    // 不适用 Object.assign 就是为了保持类的清洁，清除不必要的字段
    for (const k in json) {
      if ((this as any)[k] !== undefined) {
        (this as any)[k] = (json as any)[k]
      }
    }
    // Object.assign(this, json)
  }

  // 根据传入的数组获取模型
  public getJson (keys: string, json = {}) {
    const keyArr = keys.split(' ')
    keyArr.forEach((key) => {
      (json as any)[key] = (this as any)[key]
    })
    return json
  }

  // 删除数据
  public deleteModel () {
    return $wAxios.$delete(`${this.deleteApi}${this._id}`)
  }
}

export default BaseModel
